<?php
/**
 * Created by PhpStorm.
 * User: iiinsomnia
 * Date: 2017/11/25
 * Time: 22:08
 */
namespace App\Http\Controllers;

use App\Models\Task;
use App\Models\User;
use App\Service\TaskDailyService;
use App\Service\UserService;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;

class TaskDailyController extends Controller {
    protected $taskDaily;

    function __construct(TaskDailyService $taskDaily) {
        $this->taskDaily = $taskDaily;
    }

    public function taskDailyList(Request $request, $taskID) {
        $data = $this->taskDaily->getList($taskID, $request->all());

        return self::responseSuccess($data);
    }

    public function add(Request $request, $taskID, Application $application) {
        $input = $request->all();

        $v = Validator::make($input, [
            'content' => 'required',
            'img'     => 'required',
        ]);

        if ($v->fails()) {
            return self::responseError(1007, '参数错误');
        }

        $id = $this->taskDaily->add($taskID, $input);

        if (!$id) {
            return self::responseError(1004, '操作失败');
        }
        //发送客服消息
        $users = Task::whereId($taskID)->task_join_users;
        $users->each(function (User $user) use ($application){
            $application->staff->message('您监督的任务有新的动态, 请前往查看哦')->to($user->open_id)->send();
        });
        return self::responseSuccess(['id' => $id]);
    }

    public function upload(Request $request) {
        if (!$request->hasFile('photo')) {
            return self::responseError(1004, '操作失败');
        }

        $file = $request->file('photo');
        $user = UserService::authUser();

        $storeName = md5(sprintf("%d%s%d", $user->id, $file->getFilename(), time()));

        $path = $file->storeAs(date('Ymd'), sprintf("%s.%s", $storeName, $file->extension()));

        return self::responseSuccess(['path' => $path]);
    }

    public function praise(Request $request, $id) {
        $result = $this->taskDaily->praise($id);

        if (!$result) {
            return self::responseError(1004, '操作失败');
        }

        return self::responseSuccess();
    }
}